package com.biscuit.page.basicservice.utils;

import com.alibaba.fastjson.JSON;
import com.biscuit.page.basicservice.api.model.response.open_common.GeneratePublicPrivateKeyAResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Objects;

/**
 * @author biscuit
 * @createTime 2024/5/17 10:01
 */
@Slf4j
public class SecurityUtil {

    // 公私钥生成网址 http://web.chacuo.net/netrsakeypair

    // 公钥
    private static final String PUBLIC_KEY = "";

    // 私钥
    private static final String PRIVATER_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqeSnt7brajWgfnHZakYVwiMlt9xFNefj+fB1kP85TZH9YVBRtEp7iXS2iJhfhUZvo239OXbAo/Nvar+bklN3ZNodpIyrLqekVvWvfd5SiSQ62My7ZiONILFLn8mERnsVqJ+oE6lLjv3jnIh2BSUBHE2N6mEyyuOR1G1/BE4rOYFYyrQdaN+Obdf6z4uinm8VX5ZZOCMPp1mEROIQJG+fyAx9R6IuYwL+wZWU/2yhvZi6rr9PdVuv13QrAU2tnZW6sblzTw1Qi6GG0mHd4v165LyXVrbwmyJybkrEuMFOrdA1UyaXNMrPsGdnaGWKecedWEnYKtNSHrucPmmFxZ2KDAgMBAAECggEAPpjpRZ3y7AfawSjR6OXgqvb/iCqeJuXwAXqPzF0FpWeUv1l4eqjIwPRYKl90i19NMc9PyvXqFtLq5D2NOkhTwkwcowWv1ENa/Immz9L4ODM9fLgErwpt8vWbp+I/tJmpghaP/ygQMeMAQVcsoGnGeZLsB3tfRo1QDpRzr9E+OhNaE/pFoaxW6uWfx5FhymFBapKCKSQFbYKQYsSuhRFHsJwbx6Mj95Uo22PwuEwHscsdJiReL8gKTI3TsOPSwbBCb9YmKbdJtsPqLisB8LNeA+41tRrX/Hl+Reo5LM+9HBOHl6UfeHSysSOocZlkaFjz7uOxmAKFohvRYoQ5OtDbUQKBgQDhlQFXT1vXCPqkX+JMs6OszOz5FI6WiTkt4hu7rEFJYytrWX3pO4PZr2PQm5cOrfyHYtN/Ml6oeQ/IqUtLqgUgB5LYUwI0YWjO9gMG3Jilq8mws88hILmljzqowbqpY7TSRhL6vJsjba1xtctKkoOPwObDVpG4ktpg2ZVgM4dWKwKBgQDBddQCYUglDCFvOr8TgPZ4by+VMlkTq7I197Wy4zZUtg5Nj/xNd2fZdL+KJnRq939jIAmnt0vwrRXu8o9IHZhuYuWEZeOWDFmpFUUG9TgAc1CyQQsSIeHJ6wgOeerc/i3uhuG9WxOW8S5RbWDTvmNKrj+C4QcVDmuItRUPYQWRCQKBgEtbYIBPNWnnSPuCQHHJDONb7cnjcSKeoqhOQV93UrP2WfnZgnNYe1pL+fclEthHjPWZMPfr1q1HC9vHmiyjlmS1wvta94CSDdYdXrN7G880TQMnfgkeCoZhC4J2fSm68hvQZuS1/sleCTPUPB4kRajPEwesMq/K9wKljP3/GLXTAoGBALvfTVAyYPl5Wk7GYiDysGgssazWBCNSLfKy6EUc2fpSAnnYRlCEkNlgw1HKHmxyhcchqb6yBpFnxVETRYnnE8y/RdzZhbaFr9y/xxUGtqfZVJiHCdVGChson95PD4IlZT2qxzY4aEHBXhW9fraiwZIYvZzAIzyTkGJmWFljAyDhAoGAIFqX/qjSfYW7mva/v5RaPvDqbITfnWpJYFyJ2YgZ6Lcgw48M8Rks4NKuY4eH8FqWjmlsMM9d+VE6ZD9WZnMnyVsU2f1y+0uFkSQkKveHXUDJWHsGigD5seh45k5aga/rHkwg8SX8p2zZFTNhpGfnsggH4BHXpjdVb3V/JeooQQo=";

    /**
     * 私钥解密
     */
    public static String decrypt(String encryptBody) {
        try {
            // 加载私钥
            PrivateKey privateKey = loadPrivateKey();

            BaseExceptionUtil.throwException(StringUtils.isNotBlank(encryptBody), "加密密文为空");
            BaseExceptionUtil.throwException(Objects.nonNull(privateKey), "解密密钥为空");

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            byte[] encryptedBytes = Base64.decodeBase64(encryptBody);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("SecurityUtil decrypt 解密失败，msg -> {}，error -> {}", e.getMessage(), JSON.toJSONString(e));
        }
        return "";
    }

    /**
     * 公钥加密
     */
    public static String encrypt(String encryptBody) {
        return null;
    }

    public static GeneratePublicPrivateKeyAResp generatePublicPrivateKey() {
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(2048);
            KeyPair keyPair = generator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            String publicKeyString = Base64.encodeBase64String(publicKey.getEncoded());
            String privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
            return new GeneratePublicPrivateKeyAResp(publicKeyString, privateKeyString);
        } catch (Exception e) {
            log.error("SecurityUtil generatePublicPrivateKey 公私钥生成失败，error -> {}", JSON.toJSONString(e));
        }
        return null;
    }

    private static PrivateKey loadPrivateKey() {
        try {
            byte[] keyBytes = Base64.decodeBase64(PRIVATER_KEY);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(spec);
        } catch (Exception e) {
            log.error("SecurityUtil loadPrivateKey 加载私钥失败，message -> {}，error -> {}", e.getMessage(), JSON.toJSONString(e));
        }
        return null;
    }

}
